﻿package net.wangit.dev.table;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.TableVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.jdbc.table.TableCache;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveTableAction extends DomainAction {

	private static Version version = new TableVersion();

	public SaveTableAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newTableName = ac.getRequestParameter("table.t");
		if (!Checker.isEmpty(newTableName))
			newTableName = StringUtil.clearSpace(newTableName.toUpperCase());
		format(ac, newTableName);
		super.doAction(db, ac);
		ac.setSessionAttribute(TableUI.KEY, newTableName);
		String oldTableName = ac.getRequestParameter("table.t.k");
		if (!Checker.isEmpty(oldTableName) && oldTableName.equals(newTableName))
			ac.getActionResult().setScript(null);
		TableCache.clear(domain, oldTableName);
		TableReferenceUtil.update(db, domain, oldTableName, newTableName);
		VersionUtil.saveVersion(ac, version, domain, newTableName);
	}

	private void format(ActionContext ac, String tableName) {
		List<Table> tables = ac.getTables();
		for (int i = 0; i < tables.size(); i++) {
			Table table = tables.get(i);
			if ("TABLE".equals(table.getTableName()))
				formatTable(ac, table.getRows(), tableName);
			else if ("COLUMN".equals(table.getTableName()))
				formatColumn(table.getRows(), tableName);
		}

	}

	private void formatTable(ActionContext ac, List<ColumnRow> rows,
			String tableName) {
		if (rows.size() > 0) {
			ColumnRow row = rows.get(0);
			row.set("t", tableName);
			LockUtil.setFields(ac, row, "table");
		}
	}

	private void formatColumn(List<ColumnRow> rows, String tableName) {
		for (int i = 0; i < rows.size(); i++) {
			ColumnRow row = rows.get(i);
			row.set("t", tableName);
			String columnName = row.get("c");
			if (!Checker.isEmpty(columnName)) {
				columnName = StringUtil.clearSpace(columnName.toLowerCase());
				row.set("c", columnName);
			}
		}

	}

}
